package com.qm.controller;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.qm.service.UserService;
import com.qm.vo.QmResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisCluster;

/**
 @author james
 @create 2021-04-22 9:55
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JedisCluster jedisCluster;

    /**
     * 判断用户是否存在
     * 1.url: http://sso.qm.com/user/check/xiangyutao/1?r=0.5533364643320497&callback=jsonp1619491077955&_=1619491084883
     * 2.请求参数：param(username,password),user,callback
     * 3.返回值：JSONPObject
     */
    @RequestMapping("/check/{param}/{type}")
    public JSONPObject cheackUser(@PathVariable String param,
                                  @PathVariable Integer type, String callback) {
        boolean flag = userService.checkUser(param, type);
        QmResult qmResult = QmResult.success(flag);
        return new JSONPObject(callback, qmResult);
    }

    /**
     * 利用jsonp获取用户信息,实现用户名首页回显
     * 1.url:"http://sso.qm.com/user/query/" + _ticket
     * 2.请求参数：callback,ticket
     * 3.返回值：JSONPObject
     */
    @RequestMapping("/query/{ticket}")
    public JSONPObject findUserByTicket(String callback, @PathVariable String ticket) {
        if (jedisCluster.exists(ticket)) {
            String data = jedisCluster.get(ticket);
            return new JSONPObject(callback, new QmResult().success(data));
        } else {
            return new JSONPObject(callback, new QmResult().fail());
        }
    }

}
